<template>
  <view class="w-[100vw] h-[100vh] bg-[#f8f9ff]">
    <view class="w-[90%] m-auto flex flex-col items-center justify-start">
      <view
        class="avatar w-[120rpx] h-[120rpx] rounded-full bg-[#cce0ff] flex items-center justify-center mt-10 mb-8"
      >
        <wd-icon
          name="user"
          size="30"
          v-if="!user.avatar"
          @click="selectAvatar"
        />
        <image
          v-else
          class="w-[100%] h-[100%] object-cover rounded-full"
          :src="userInfo.avatar"
          @click="selectAvatar"
        />
      </view>

      <!-- 昵称 -->
      <view class="w-[100%] mb-6">
        <text class="text-base font-medium mb-2 block">昵称</text>
        <input
          type="text"
          v-model="userInfo.nickname"
          placeholder="请输入昵称"
        />
      </view>

      <!-- 性别 -->
      <view class="w-full mb-6 flex flex-col items-start">
        <text class="text-base font-medium mr-4">邮箱</text>
        <input type="text" v-model="userInfo.email" placeholder="请输入邮箱" />
      </view>

      <!-- 签名 -->
      <view class="w-full mb-6">
        <text class="text-base font-medium mb-2 block">签名</text>
        <input
          type="text"
          v-model="userInfo.signature"
          placeholder="请输入个性签名"
        />
      </view>

      <!-- 密码 -->
      <view class="w-full mb-10 relative">
        <text class="text-base font-medium mb-2 block">密码</text>
        <input
          :type="showPassword ? 'text' : 'password'"
          v-model="userInfo.password"
          placeholder="请输入密码"
        />
        <wd-icon
          :name="showPassword ? 'eye-off' : 'eye'"
          class="absolute right-4 top-[28rpx] text-[#999] text-[28rpx]"
          @click="showPassword = !showPassword"
        />
      </view>

      <!-- 保存按钮 -->
      <button
        class="w-full h-[60rpx] rounded-[12rpx] bg-[#3ea0ff] text-white text-lg font-medium"
        @click="save"
      >
        保存
      </button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { uploadImage } from '@/utils/upload'
import { update } from '@/api/user.api'
import { backTo } from '@/utils/unifunc'

const user = uni.getStorageSync('user') as UserInfo

const userInfo = reactive({
  avatar: user.avatar || '',
  nickname: user.nickname || '',
  signature: user.userSign || '',
  email: user.email || '',
  password: ''
})
const showPassword = ref(false)

const selectAvatar = async () => {
  const res = await uploadImage()
  if (res) {
    userInfo.avatar = res
  }
}

async function save() {
  const data = {
    nickname: userInfo.nickname,
    email: userInfo.email,
    signature: userInfo.signature,
    password: userInfo.password,
    avatar: userInfo.avatar,
    userId: user.id
  }
  const res = await update<typeof data>(data)
  if (res.code === 200) {
    backTo()
  }
}
</script>

<style lang="scss" scoped></style>
